<template>
  <div class="sidebar">
    <div class="sidebar-header">
      <h3>AgChat聊天</h3>
      <div class="header-actions">
        <button class="btn-icon" @click="showSearch = true">
          <Icon icon="mdi:magnify" />
        </button>
        <button class="btn-icon" @click="showAddMenu = !showAddMenu">
          <Icon icon="mdi:plus" />
        </button>
        <div v-if="showAddMenu" class="add-menu">
          <button @click="showAddFriend = true">添加好友</button>
          <button @click="showCreateGroup = true">创建群聊</button>
        </div>
      </div>
    </div>
    <div class="sidebar-content">
      <div class="chat-tabs">
        <button 
          :class="['tab', { active: activeTab === 'chats' }]" 
          @click="activeTab = 'chats'"
        >
          聊天
        </button>
        <button 
          :class="['tab', { active: activeTab === 'contacts' }]" 
          @click="activeTab = 'contacts'"
        >
          联系人
        </button>
        <button 
          :class="['tab', { active: activeTab === 'groups' }]" 
          @click="activeTab = 'groups'"
        >
          群聊
        </button>
      </div>
      
      <div v-if="activeTab === 'chats'" class="chat-list">
        <div 
          v-for="friend in friends" 
          :key="friend.id" 
          :class="['chat-item', { active: currentChat?.type === 'private' && currentChat.id === friend.id }]"
          @click="selectChat({ type: 'private', id: friend.id, name: friend.username, avatar: friend.avatar })"
        >
          <img :src="friend.avatar" class="avatar" />
          <div class="chat-info">
            <div class="chat-name">{{ friend.username }}</div>
            <div class="chat-status">
              <span :class="['status-dot', friend.status]"></span>
              {{ friend.status === 'online' ? '在线' : `最后在线: ${formatTime(friend.lastSeen)}` }}
            </div>
          </div>
          <div v-if="friend.unreadCount > 0" class="unread-count">
            {{ friend.unreadCount }}
          </div>
        </div>
        
        <div 
          v-for="group in groups" 
          :key="group.id" 
          :class="['chat-item', { active: currentChat?.type === 'group' && currentChat.id === group.id }]"
          @click="selectChat({ type: 'group', id: group.id, name: group.name, avatar: group.avatar })"
        >
          <img :src="group.avatar" class="avatar" />
          <div class="chat-info">
            <div class="chat-name">{{ group.name }}</div>
            <div class="chat-members">{{ group.members.length }} 成员</div>
          </div>
          <div v-if="group.unreadCount > 0" class="unread-count">
            {{ group.unreadCount }}
          </div>
        </div>
      </div>
      
      <div v-if="activeTab === 'contacts'" class="contact-list">
        <div class="list-header">好友列表</div>
        <div 
          v-for="friend in friends" 
          :key="friend.id" 
          class="contact-item"
        >
          <img :src="friend.avatar" class="avatar" />
          <div class="contact-info">
            <div class="contact-name">{{ friend.username }}</div>
            <div class="contact-status">
              <span :class="['status-dot', friend.status]"></span>
              {{ friend.status === 'online' ? '在线' : '离线' }}
            </div>
          </div>
          <button class="btn-icon" @click="removeFriend(friend.id)">
            <Icon icon="mdi:delete" />
          </button>
        </div>
        <div class="list-header">好友申请</div>
        <div 
          v-for="request in requests" 
          :key="request.id" 
          class="request-item"
        >
          <img :src="request.user.avatar" class="avatar" />
          <div class="request-info">
            <div class="request-name">{{ request.user.username }}</div>
            <div class="request-message">{{ '请求添加您为好友' }}</div> <!-- request.verificationMessage ||  -->
            <div class="request-time">{{ formatTime(request.createdAt) }}</div>
          </div>
          <div class="request-actions">
            <button class="btn btn-primary btn-sm" @click="respondToRequest(request.id, true)">接受</button>
            <button class="btn btn-secondary btn-sm" @click="respondToRequest(request.id, false)">拒绝</button>
          </div>
        </div>
      </div>
      
      <div v-if="activeTab === 'groups'" class="group-list">
        <div class="list-header">群聊列表</div>
        <div 
          v-for="group in groups" 
          :key="group.id" 
          class="group-item"
        >
          <img :src="group.avatar" class="avatar" />
          <div class="group-info">
            <div class="group-name">{{ group.name }}</div>
            <div class="group-members">{{ group.members.length }} 成员</div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 搜索模态框 -->
    <div v-if="showSearch" class="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>搜索用户</h3>
          <button class="btn-icon" @click="showSearch = false">
            <Icon icon="mdi:close" />
          </button>
        </div>
        <div class="modal-body">
          <input 
            v-model="searchQuery" 
            type="text" 
            placeholder="输入用户名或邮箱" 
            class="input"
            @input="debouncedSearch"
          />
          <div v-if="searchResults.length" class="search-results">
            <div 
              v-for="user in searchResults" 
              :key="user.id" 
              class="search-result-item"
            >
              <img :src="user.avatar" class="avatar" />
              <div class="user-info">
                <div class="user-name">{{ user.username }}</div>
                <div class="user-email">{{ user.email }}</div>
              </div>
              <button 
                v-if="!user.isFriend" 
                class="btn btn-primary btn-sm"
                @click="addFriend(user.id)"
              >
                添加好友
              </button>
              <span v-else class="friend-label">已是好友</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加好友模态框 -->
    <div v-if="showAddFriend" class="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>添加好友</h3>
          <button class="btn-icon" @click="showAddFriend = false">
            <Icon icon="mdi:close" />
          </button>
        </div>
        <div class="modal-body">
          <input 
            v-model="friendSearchQuery" 
            type="text" 
            placeholder="输入用户名或邮箱" 
            class="input"
            @input="debouncedFriendSearch"
          />
          <div v-if="friendSearchResults.length" class="search-results">
            <div 
              v-for="user in friendSearchResults" 
              :key="user.id" 
              class="search-result-item"
            >
              <img :src="user.avatar" class="avatar" />
              <div class="user-info">
                <div class="user-name">{{ user.username }}</div>
                <div class="user-email">{{ user.email }}</div>
              </div>
              <button 
                v-if="!user.isFriend" 
                class="btn btn-primary btn-sm"
                @click="sendFriendRequest(user.id)"
              >
                发送请求
              </button>
              <span v-else class="friend-label">已是好友</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 创建群组模态框 -->
    <div v-if="showCreateGroup" class="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>创建群聊</h3>
          <button class="btn-icon" @click="showCreateGroup = false">
            <Icon icon="mdi:close" />
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>群名称</label>
            <input v-model="groupName" type="text" class="input" />
          </div>
          <div class="form-group">
            <label>群描述</label>
            <textarea v-model="groupDescription" class="input"></textarea>
          </div>
          <div class="form-group">
            <label>选择成员</label>
            <div class="member-selection">
              <div 
                v-for="friend in friends" 
                :key="friend.id" 
                :class="['member-item', { selected: selectedMembers.includes(friend.id) }]"
                @click="toggleMemberSelection(friend.id)"
              >
                <img :src="friend.avatar" class="avatar" />
                <div class="member-name">{{ friend.username }}</div>
              </div>
            </div>
          </div>
          <button class="btn btn-primary" @click="createGroup">创建群聊</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { Icon } from '@iconify/vue';
import { useChatStore } from '@/stores/chat'
import { useAuthStore } from '@/stores/auth'
import { debounce } from 'lodash-es'

const chatStore = useChatStore()
const authStore = useAuthStore()

const activeTab = ref('chats')
const showSearch = ref(false)
const showAddMenu = ref(false)
const showAddFriend = ref(false)
const showCreateGroup = ref(false)
const searchQuery = ref('')
const friendSearchQuery = ref('')
const groupName = ref('')
const groupDescription = ref('')
const selectedMembers = ref([])

const friends = computed(() => chatStore.friends)
const requests = computed(() => chatStore.requests)
const groups = computed(() => chatStore.groups)
const currentChat = computed(() => chatStore.currentChat)
const searchResults = computed(() => chatStore.users)
const friendSearchResults = computed(() => chatStore.users)

onMounted(async () => {
  await chatStore.loadFriends()
  await chatStore.loadFriendRequests()
  await chatStore.loadGroups()
  chatStore.setupSignalRHandlers()
})

const selectChat = (chat) => {
  chatStore.currentChat = chat
  chatStore.messages = []
  
  if (chat.type === 'private') {
    chatStore.loadPrivateMessages(chat.id)
    chatStore.markAllAsRead(chat.id, null)
  } else {
    chatStore.loadGroupMessages(chat.id)
    chatStore.markAllAsRead(null, chat.id)
  }
}

const debouncedSearch = debounce(() => {
  if (searchQuery.value) {
    chatStore.searchUsers(searchQuery.value)
  }
}, 500)

const debouncedFriendSearch = debounce(() => {
  if (friendSearchQuery.value) {
    chatStore.searchUsers(friendSearchQuery.value)
  }
}, 500)

const addFriend = async (userId) => {
  const result = await chatStore.addFriend(userId)
  if (result.success) {
    showSearch.value = false
    searchQuery.value = ''
  }
}

const sendFriendRequest = async (userId) => {
  const result = await chatStore.addFriend(userId)
  if (result.success) {
    showAddFriend.value = false
    friendSearchQuery.value = ''
  }
}

const respondToRequest = async (friendshipId, accept) => {
  const result = await chatStore.respondToRequest(friendshipId, accept)
  if (!result.success) {
    alert(result.message)
  }
}

const removeFriend = async (friendId) => {
  const result = await chatStore.removeFriend(friendId)
  if (!result.success) {
    alert(result.message)
  }
}

const toggleMemberSelection = (memberId) => {
  const index = selectedMembers.value.indexOf(memberId)
  if (index === -1) {
    selectedMembers.value.push(memberId)
  } else {
    selectedMembers.value.splice(index, 1)
  }
}

const createGroup = async () => {
  if (!groupName.value) {
    alert('请输入群名称')
    return
  }
  
  if (selectedMembers.value.length === 0) {
    alert('请选择至少一个成员')
    return
  }
  
  const groupData = {
    name: groupName.value,
    description: groupDescription.value,
    memberIds: selectedMembers.value
  }
  
  const result = await chatStore.createGroup(groupData)
  if (result.success) {
    showCreateGroup.value = false
    groupName.value = ''
    groupDescription.value = ''
    selectedMembers.value = []
    activeTab.value = 'chats'
  } else {
    alert(result.message)
  }
}

const formatTime = (time) => {
  const date = new Date(time)
  return date.toLocaleTimeString()
}
</script>

<style scoped>
.sidebar {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.sidebar-header {
  padding: 1rem;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
}

.sidebar-header h3 {
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 0.5rem;
  position: relative;
}

.btn-icon {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0.5rem;
  border-radius: 4px;
}

.btn-icon:hover {
  background-color: #f0f0f0;
}

.add-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
  width: 88px;
}

.add-menu button {
  display: block;
  width: 100%;
  padding: 0.5rem 1rem;
  background: none;
  border: none;
  text-align: left;
  cursor: pointer;
}

.add-menu button:hover {
  background-color: #f0f0f0;
}

.sidebar-content {
  flex: 1;
  overflow-y: auto;
}

.chat-tabs {
  display: flex;
  border-bottom: 1px solid #e0e0e0;
  background-color: white;
}

.tab {
  flex: 1;
  padding: 0.75rem;
  background: none;
  border: none;
  cursor: pointer;
  border-bottom: 2px solid transparent;
}

.tab.active {
  border-bottom-color: #07c160;
  color: #07c160;
}

.chat-list,
.contact-list,
.group-list {
  padding: 0.5rem;
}

.chat-item,
.contact-item,
.group-item {
  display: flex;
  align-items: center;
  padding: 0.75rem;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 0.25rem;
}

.chat-item:hover,
.contact-item:hover,
.group-item:hover {
  background-color: #f0f0f0;
}

.chat-item.active {
  background-color: #e0f0e0;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  margin-right: 0.75rem;
}

.chat-info,
.contact-info,
.group-info {
  flex: 1;
}

.chat-name,
.contact-name,
.group-name {
  font-weight: 500;
}

.chat-status,
.contact-status,
.group-members {
  font-size: 0.75rem;
  color: #999;
}

.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 0.25rem;
}

.status-dot.online {
  background-color: #07c160;
}

.status-dot.offline {
  background-color: #999;
}

.unread-count {
  background-color: #fa5151;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.75rem;
}

.list-header {
  padding: 0.75rem;
  font-weight: 500;
  background-color: white;
  border-bottom: 1px solid #e0e0e0;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  padding: 1rem;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-body {
  padding: 1rem;
}

.search-results {
  margin-top: 1rem;
}

.search-result-item {
  display: flex;
  align-items: center;
  padding: 0.75rem;
  border-bottom: 1px solid #f0f0f0;
}

.user-info {
  flex: 1;
  margin-left: 0.75rem;
}

.user-name {
  font-weight: 500;
}

.user-email {
  font-size: 0.75rem;
  color: #999;
}

.request-item {
  display: flex;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #f0f0f0;
}

.request-item:last-child {
  border-bottom: none;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 1rem;
}

.request-info {
  flex: 1;
}

.sender-name {
  font-weight: 500;
  margin-bottom: 0.25rem;
}

.request-message {
  color: #666;
  font-size: 0.9rem;
  margin-bottom: 0.25rem;
}

.request-time {
  color: #999;
  font-size: 0.8rem;
}

.request-actions {
  display: flex;
  gap: 0.5rem;
}

.btn {
  padding: 0.25rem 0.75rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.875rem;
}

.btn-primary {
  background-color: #07c160;
  color: white;
}

.btn-primary:hover {
  background-color: #06ae56;
}

.btn-secondary {
  background-color: #f0f0f0;
  color: #333;
}

.btn-secondary:hover {
  background-color: #e0e0e0;
}

.btn-sm {
  padding: 0.25rem 0.5rem;
  font-size: 0.75rem;
}

.friend-label {
  color: #07c160;
  font-size: 0.75rem;
}

.member-selection {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 0.5rem;
  margin-top: 0.5rem;
}

.member-item {
  display: flex;
  align-items: center;
  padding: 0.5rem;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  cursor: pointer;
}

.member-item.selected {
  border-color: #07c160;
  background-color: #f0f9f0;
}

.member-name {
  margin-left: 0.5rem;
  font-size: 0.875rem;
}
</style>